#include <stdlib.h>
#include <stdio.h>
#include "timeit.h"
#include "log.h"


long usecs_offset(struct timeval *from, struct timeval *to)
{
	return (to->tv_sec - from->tv_sec) * 1000000 + (to->tv_usec - from->tv_usec);
}


void timeit_reset(timeit_info_t *ti)
{
	ti->usecs = 0;
	ti->begin.tv_sec = 0;
	ti->begin.tv_usec = 0;
	ti->end.tv_sec = 0;
	ti->end.tv_usec = 0;
}

void timeit_start(timeit_info_t *ti)
{
	ti->usecs = 0;
	gettimeofday(&ti->begin, NULL);
	ti->end.tv_sec = 0;
	ti->end.tv_usec = 0;

	log_debug("[timeit] timeit_start: begin: %ld:%ld, end: %ld:%ld, elasped_usec: %ld\n",
			ti->begin.tv_sec, ti->begin.tv_usec,
			ti->end.tv_sec, ti->end.tv_usec,
			ti->usecs);
}

void timeit_pause(timeit_info_t *ti)
{
	gettimeofday(&ti->end, NULL);
	ti->usecs += usecs_offset(&ti->begin, &ti->end);

	log_debug("[timeit] timeit_pause: begin: %ld:%ld, end: %ld:%ld, elasped_usec: %ld\n",
			ti->begin.tv_sec, ti->begin.tv_usec,
			ti->end.tv_sec, ti->end.tv_usec,
			ti->usecs);

	ti->begin.tv_sec = 0;
	ti->begin.tv_usec = 0;
	ti->end.tv_sec = 0;
	ti->end.tv_usec = 0;
}

void timeit_resume(timeit_info_t *ti)
{
	gettimeofday(&ti->begin, NULL);

	log_debug("[timeit] timeit_resume: begin: %ld:%ld, end: %ld:%ld, elasped_usec: %ld\n",
			ti->begin.tv_sec, ti->begin.tv_usec,
			ti->end.tv_sec, ti->end.tv_usec,
			ti->usecs);
}

long timeit_stop(timeit_info_t *ti)
{
	long elasped_usec = 0;

	gettimeofday(&ti->end, NULL);
	ti->usecs += usecs_offset(&ti->begin, &ti->end);

	log_debug("[timeit] timeit_stop: begin: %ld:%ld, end: %ld:%ld, elasped_usec: %ld\n",
			ti->begin.tv_sec, ti->begin.tv_usec,
			ti->end.tv_sec, ti->end.tv_usec,
			ti->usecs);

	elasped_usec = ti->usecs;

	timeit_reset(ti);
	return elasped_usec;
}

